package com.lwy.setter2;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 枚举填充器
 *
 * @author lwy
 */
@Slf4j
public class StuffEnumImpl implements IStuffer<StuffEnum> {

    @Override
    public <T> void stuff(StuffEnum annotation, Field originField, Collection<T> origins) throws IllegalAccessException {
        if (CollUtil.isEmpty(origins)) {
            return;
        }
        final Class<? extends Enum<?>> enumClass = annotation.enumClass();
        final Map<String, Object> originFieldMap = EnumUtil.getNameFieldMap(enumClass, annotation.originEnumField());
        final Map<String, Object> targetFieldMap = EnumUtil.getNameFieldMap(enumClass, annotation.targetEnumField());
        final Map<Object, Object> mapping = new HashMap<>();
        originFieldMap.forEach((enumName, originFieldValue) -> mapping.put(originFieldValue, targetFieldMap.get(enumName)));
        // 填充值
        for (T origin : origins) {
            Object mappingValue = mapping.get(originField.get(origin));
            if (mappingValue != null) {
                ReflectUtil.setFieldValue(origin, annotation.targetField(), mappingValue);
            }
        }
    }
}

